package rpc

import (
	"context"

	"google.golang.org/grpc"

	pb "bilinadmin/api/pb/server"
	"bilinadmin/internal/service"
)

type empHandler struct {
	*RpcBase
	pb.UnimplementedBilinEmployeeServer
	name string
}

func NewEmployeeHandler() *empHandler {
	return &empHandler{
		RpcBase:                          base,
		UnimplementedBilinEmployeeServer: pb.UnimplementedBilinEmployeeServer{},
		name:                             "rpc_employee_handler",
	}
}

// Register 注册服务
func (e *empHandler) Register(s *grpc.Server) {
	pb.RegisterBilinEmployeeServer(s, e)
}

// EmployeeCreate 创建员工
func (e *empHandler) EmployeeCreate(ctx context.Context, req *pb.EmployeeCreateRequest) (*pb.EmployeeResponse, error) {
	if req == nil {
		return nil, nil
	}
	acc, errL := service.GetService().VerifyAccountToken(req.AccountToken)
	if errL != nil {
		return nil, errL
	}
	return service.GetEmployeeService().CreateEmployee(ctx, req.BrandId, acc.UserName, acc.Mobile, acc.Email, acc.GID)
}

// LoginAdmin 登陆后台
func (e *empHandler) LoginAdmin(ctx context.Context, req *pb.EmployeeLoginReq) (*pb.EmployeeLoginReply, error) {
	if req == nil {
		return nil, nil
	}
	token, errL := service.GetService().VerifyAccountToken(req.Token)
	if errL != nil {
		return nil, errL
	}
	ret, errL := service.GetEmployeeService().LoginBilin(ctx, req.BrandId, token.GID)
	if errL != nil {
		return nil, errL
	}
	ret.Token, errL = service.GetService().GenBilinToken(token.GID, ret.EmpName, ret.BrandId, ret.EmpId)
	if errL != nil {
		return nil, errL
	}
	return ret, nil
}

// EmployeeBriefInfoGetById 根据id获取简要员工信息
func (e *empHandler) EmployeeBriefInfoGetById(ctx context.Context, req *pb.EmployeeGetByIdReq) (*pb.EmployeeInfoBriefReply, error) {
	if req == nil {
		return nil, nil
	}
	return service.GetEmployeeService().GetEmployeeInfoBrief(ctx, req.BrandId, req.EmpId)
}

// GetEmployeeBriefInfoByBrandAndAccount 通过brand_id和account_token获取员工简单信息
func (e *empHandler) GetEmployeeBriefInfoByBrandAndAccount(ctx context.Context, req *pb.GetEmployeeBriefInfoByBrandAndAccountReq) (*pb.EmployeeInfoBriefReply, error) {
	if req == nil {
		return nil, nil
	}
	token, errL := service.GetService().VerifyAccountToken(req.AccountToken)
	if errL != nil {
		return nil, errL
	}
	ret, errL := service.GetEmployeeService().GetEmpByBrandAndGID(ctx, req.BrandId, token.GID)
	if errL != nil {
		return nil, errL
	}
	return ret, nil
}

// CredibleConfirmEmployee 服务端可信确认员工
func (e *empHandler) CredibleConfirmEmployee(ctx context.Context, req *pb.CredibleConfirmEmployeeReq) (*pb.EmptyResp, error) {
	if req == nil {
		return nil, nil
	}
	errL := service.GetEmployeeService().CredibleConfirmEmployee(ctx, req)
	if errL != nil {
		return nil, errL
	}
	return &pb.EmptyResp{}, nil
}
